package com.lu.stack.gateway.filter.global;

import cn.hutool.core.util.ReUtil;
import com.alibaba.fastjson.JSON;
import com.lu.stack.gateway.filter.GatewayContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.InetAddress;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author zhanglu
 * @project lu-cloud-stack
 * @description 日志全局过滤器
 * @date 2023/2/5 18:32
 */
@Slf4j
@Component
public class LogGlobalFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        InetAddress address = request.getRemoteAddress().getAddress();
        String realIp = address.getHostAddress();
        String servletPath = exchange.getRequest().getPath().toString();
        Map<String, Object> requestParams = new HashMap<>();
        Map<String, Object> header = new LinkedHashMap<>();
        request.getHeaders().forEach((k, v) -> {
            if(ReUtil.isMatch("Cookie", k)){
                header.put(k, v);
            }
        });
        requestParams.put("header", header);
        requestParams.put("params", request.getQueryParams());
        requestParams.put("body", ((GatewayContext) exchange.getAttribute(GatewayContext.CACHE_GATEWAY_CONTEXT)).getJsonBody());
        log.info("请求ip:{}---访问路径:{}---请求参数:{}", realIp, servletPath, JSON.toJSONString(requestParams));
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE + 1;
    }

    /**
     * 从dataBuffer缓冲区中获取request请求的body内容（注意：基于netty下所有的请求数据会写入到dataBuffer中）
     * @param dataBuffer
     * @return
     */
    private String getBodyContent(DataBuffer dataBuffer){
        int count = dataBuffer.readableByteCount();
        if (count > 0) {
            byte[] bytes = new byte[count];
            dataBuffer.read(bytes);
            DataBufferUtils.release(dataBuffer);
            return new String(bytes, StandardCharsets.UTF_8);
        }
        return null;
    }


}
